// pages/wine/wine.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit: 20,
    page: 1,
    total_page: 0,
    wineList: [], //列表
    hasMore: true,
    wineDome: true,
    numbers: 1,
    buyGoods: [], //购买商品信息 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.setData({
      wineList: [],
      page: 1,
      total_page: 0,
      wineDome: true
    })
    this.wineList();
  },

  //页面下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    setTimeout(function () {
      that.resetData()
    }, 1000)
  },
  //刷新页面
  resetData: function () {
    var that = this
    that.setData({
      page: 1,
      // hasMore: true
    });
    that.wineList();
  },

  //页面上拉触底
  onReachBottom: function (e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function () {
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.wineList();
  },

  //酒柜列表
  wineList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          if (currentPage == 1) {
            var itemData = resultList;
            if (itemData.length >= 1) {
              //有数据
            } else {
              //无数据
            }
          } else {
            var itemData = that.data.wineList.concat(resultList)
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            total_page: totalPage,
            wineList: itemData
          });

        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("登录失败，请检查网络");
      }
    })
  },

  // 已购买商品详情
  goodsInfo: function (e) {
    var goodsInfo = e.currentTarget.dataset.goodsInfo;
    wx.navigateTo({
      url: '../wineGoods/wineGoods?sku_code=' + goodsInfo.sku_code
    })
  },

  //立即购买
  buyNow: function (e) {
    var goodsInfo = e.currentTarget.dataset.goodsInfo;
    this.setData({
      buyGoods: goodsInfo,
      numbers: 1,
      wineDome: false
    })
  },

  closeBuy: function () {
    this.setData({
      wineDome: true
    })
  },

  addNum: function () {
    var num = this.data.numbers;
    num++;
    this.setData({
      numbers: num
    })
  },
  minusNum: function () {
    var num = this.data.numbers;
    if (num > 1) {
      num--;
      this.setData({
        numbers: num
      })
    }
  },

  // 支付订单
  payOrder: function () {
    var that = this;
    var buyGoods = that.data.buyGoods;
    var params = new Object()
    params.record = [];
    var list = [];
    var box = {};
    box.sku_code = buyGoods.sku_code
    box.num = that.data.numbers
    list.push(box);
    params.record = JSON.stringify(list)
    params.buy_type = 1;
    util.showLoading("加载中");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          wx.removeStorageSync('shopId')
          that.wxPayOrder(res.data.data.result.oid, res.data.data.result.type);
        } else if (res.data.code == "2499") {
          util.showError("库存不足");
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //支付接口
  wxPayOrder: function (oid, types) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: { oid: oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              // that.wineList(); //获取酒柜列表
            },
            fail: function (error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderData');
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //配送按钮
  peisong: function (e) {
    wx.navigateTo({
      url: '../wineDistribution/wineDistribution'
    })
  },
  //取货按钮
  pickUp: function (e) {
    wx.navigateTo({
      url: '../wineSelfGet/wineSelfGet'
    })
  },
  move: function () {

  },
  //拆分数组
  split_array: function (arr, len) {
    var a_len = arr.length;
    var box_arr = [];
    var new_arr = [];
    for (var i = 0; i < a_len; i += len) {
      box_arr.push(arr.slice(i, i + len));
    }
    if (box_arr.length < 4) {
      var arr_new = [];
      for (var n = box_arr.length; n < 4; n++) {
        box_arr.push(arr_new);
      }
    }
    console.log(box_arr);
  }
})